package com.yyx.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.yyx.server.pojo.Employee;
import com.yyx.server.pojo.Notice;
import com.yyx.server.service.ElasticsearchService;
import com.yyx.server.service.EmployeeService;
import com.yyx.server.service.NoticeService;
import com.yyx.server.vo.ResultVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author YongXin
 * @date Created in 2021/10/2 15:20
 */
@Service
public class ElasticsearchServiceImpl implements ElasticsearchService {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     *将数据库中的数据添加到ES中
     * @return
     */
    @Override
    public ResultVo updEs() {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("3m");
        List<Notice> noticeList = noticeService.list();
        List<Employee> employeeList = employeeService.list();
//        for (Employee employee : employeeList) {
//            bulkRequest.add(
//                    new IndexRequest("ows_notice")
//                    .id(String.valueOf(employee.getId()))
//                    .source(JSON.toJSONString(employee), XContentType.JSON));
//        }
        for (Notice notice : noticeList) {
            bulkRequest.add(
                   new IndexRequest("ows_notice")
                   .id(String.valueOf(notice.getId()))
                   .source(JSON.toJSONString(notice), XContentType.JSON));
            }
        BulkResponse bulkResponse = null;
        try {
            bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!bulkResponse.hasFailures()){
             return ResultVo.success("添加成功");
        }
        return ResultVo.error("添加失败");
    }
}
